# backend/main.py - 更新导入部分
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from typing import AsyncIterator
from backend.api.v1 import (
    auth, subscription, nodes, users, user_subscriptions, captcha, wireguard
)
from backend.database import engine
from backend.models.user import User
from backend.core.config import settings
import logging

logging.basicConfig(level=logging.DEBUG)

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # 创建所有表
    async with engine.begin() as conn:
        await conn.run_sync(User.metadata.create_all)
    yield

app = FastAPI(
    title="可控制的轻量级 VPN 系统 API",
    description="基于 FastAPI 的现代化 SaaS 架构",
    version="1.0.0",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def read_root():
    return {"message": "可控制的轻量级 VPN 系统", "文档": "/docs"}

@app.get("/health")
def health_check():
    return {"status": "healthy"}

# 注册路由 - 确保所有路由都正确注册
app.include_router(auth.router, prefix=settings.API_V1_STR)
app.include_router(users.router, prefix=settings.API_V1_STR)
app.include_router(subscription.router, prefix=settings.API_V1_STR)
app.include_router(nodes.router, prefix=settings.API_V1_STR)
app.include_router(user_subscriptions.router, prefix=settings.API_V1_STR)
app.include_router(captcha.router, prefix=settings.API_V1_STR)
app.include_router(wireguard.router, prefix=settings.API_V1_STR)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("backend.main:app", host="0.0.0.0", port=8000, reload=True)